﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Chip8.Core.Display;
using Chip8.Core.Input;
using Chip8.Core.Memory;
using Chip8.Core.Processor;
using Chip8.Core.Timer;

namespace Chip8.Core.Bus
{
	internal class SystemBus 
	{
		public SystemBus()
		{
			CPU = new CPU(this);
			RAM = new RAM(this);
			Screen = new Screen(this);
			DelayTimer = new DelayTimer(this);
			SoundTimer = new SoundTimer(this);
			KeyPad = new ConsoleKeypad(this);
		}

		public ICPU CPU { get; private set; }
		public RAM RAM { get; private set; }
		public Screen Screen { get; private set; }
		public DelayTimer DelayTimer { get; private set; }
		public SoundTimer SoundTimer { get; private set; }
		public IKeypad KeyPad { get; private set; }

		public void Tick()
		{
			foreach (var device in _devices)
			{
				device.Tick();
			}
		}

		public void Reset()
		{
			foreach (var device in _devices)
			{
				device.Reset();
			}
		}

		public void RegisterDevice(IDevice device)
		{
			if (device == null)
			{
				throw new ArgumentNullException("device");
			}
			if (_devices.Contains(device))
			{
				throw new ArgumentException("Device already enumerated.");
			}
			_devices.Add(device);
		}

		private readonly List<IDevice> _devices = new List<IDevice>();
	}
}
